// 从sessionStorage获取保存的最高分，如果没有则默认为0
const savedBestScore = sessionStorage.getItem('bestScore');
const initialBestScore = savedBestScore ? parseInt(savedBestScore, 10) : 0;

export default {
  namespaced: true, // 启用命名空间
  state: {
    score: 0, // 当前得分
    bestScore: initialBestScore // 最高得分
  },
  mutations: {
    // 更新当前得分的mutation
    setScore(state, score) {
      state.score = score;
      // console.log("当前得分为：", state.score)
      
      // 更新最高分
      if (state.score > state.bestScore) {
        state.bestScore = state.score;
        // 保存到sessionStorage
        sessionStorage.setItem('bestScore', state.bestScore.toString());
      }
    },
    
    // 重置当前得分的mutation
    resetScore(state) {
      state.score = 0;
      // console.log("得分已重置")
    },
    
    // 设置最高分的mutation
    setBestScore(state, bestScore) {
      state.bestScore = bestScore;
      // 保存到sessionStorage
      sessionStorage.setItem('bestScore', bestScore.toString());
    },
    
    // 从sessionStorage初始化最高分
    initBestScore(state) {
      const savedBestScore = sessionStorage.getItem('bestScore');
      if (savedBestScore) {
        state.bestScore = parseInt(savedBestScore, 10);
      }
    }
  },
  actions: {
    // 更新得分的action
    updateScore({ commit }, score) {
      commit('setScore', score)
    },
    
    // 重置得分的action
    resetScore({ commit }) {
      commit('resetScore')
    },
    
    // 更新最高分的action
    updateBestScore({ commit }, bestScore) {
      commit('setBestScore', bestScore)
    },
    
    // 初始化最高分的action
    initBestScore({ commit }) {
      commit('initBestScore')
    }
  },
  getters: {
    // 获取当前得分的getter
    score: (state) => state.score,
    
    // 获取最高得分的getter
    bestScore: (state) => state.bestScore,
    
    // 检查当前得分是否为最高分的getter
    isBestScore: (state) => state.score >= state.bestScore && state.score > 0
  }
}